<template>
  <div class="user-profile-container">
    <frontend-header />
    
    <div class="container">
      <div class="page-header">
        <h1>个人中心</h1>
        <p>管理您的个人信息和账户设置</p>
      </div>
      
      <div class="content-wrapper">
      <!-- 侧边导航 -->
      <div class="sidebar">
        <div class="user-info-card">
          <div class="avatar-container">
            <img :src="userInfo.avatar" :alt="userInfo.name" class="user-avatar">
          </div>
          <h3>{{ userInfo.name || userInfo.username }}</h3>
          <p class="user-email">{{ userInfo.email || '未设置邮箱' }}</p>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          class="profile-menu"
          router
        >
          <el-menu-item index="/user/profile">
            <el-icon><User /></el-icon>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="/user/courses">
            <el-icon><VideoPlay /></el-icon>
            <span>我的课程</span>
          </el-menu-item>
          <el-menu-item index="/user/orders">
            <el-icon><Document /></el-icon>
            <span>我的订单</span>
          </el-menu-item>
        </el-menu>
      </div>
      
      <!-- 主要内容 -->
      <div class="main-content">
        <el-card shadow="hover" class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" @click="toggleEditMode" size="small">{{ editMode ? '取消' : '编辑' }}</el-button>
            </div>
          </template>
          
          <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="100px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="profileForm.name" :disabled="!editMode"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" :disabled="!editMode" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" :disabled="!editMode" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="profileForm.gender" :disabled="!editMode">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
                <el-radio label="保密">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="profileForm.age" type="number" :disabled="!editMode" placeholder="请输入年龄"></el-input>
            </el-form-item>
            <el-form-item label="注册时间">
              <el-input v-model="userInfo.createTime" disabled></el-input>
            </el-form-item>
            
            <el-form-item v-if="editMode">
              <el-button type="primary" @click="handleSaveProfile">保存</el-button>
              <el-button @click="toggleEditMode">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <el-card shadow="hover" class="password-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      </div>
    </div>
    
    <FrontendFooter />
  </div>
</template>

<script setup>
import FrontendHeader from '../../components/FrontendHeader.vue'
import FrontendFooter from '../../components/FrontendFooter.vue'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { User, VideoPlay, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

// 用户信息
const userInfo = reactive({
  id: '',
  username: '',
  name: '',
  email: '',
  phone: '',
  avatar: 'https://picsum.photos/100/100?random=1',
  createTime: ''
})

// 编辑模式
const editMode = ref(false)

// 个人信息表单
const profileForm = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  gender: '保密',
  age: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  age: [
    { type: 'number', min: 1, max: 120, message: '请输入有效的年龄', trigger: 'blur' }
  ]
}

// 验证确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 表单引用
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 计算当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 加载用户信息
const loadUserInfo = () => {
  // 这里应该调用API获取用户信息
  // 暂时使用模拟数据
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    const parsedUserInfo = JSON.parse(storedUserInfo)
    Object.assign(userInfo, {
      ...parsedUserInfo,
      name: parsedUserInfo.name || '未设置姓名',
      email: parsedUserInfo.email || '',
      phone: parsedUserInfo.phone || '',
      createTime: parsedUserInfo.createTime || '2023-01-01'
    })
  } else {
    // 模拟数据
    Object.assign(userInfo, {
      id: 1,
      username: 'testuser',
      name: '测试用户',
      email: 'test@example.com',
      phone: '13800138000',
      avatar: 'https://picsum.photos/100/100?random=1',
      createTime: '2023-01-01 10:00:00'
    })
  }
  
  // 初始化表单数据
  Object.assign(profileForm, {
    username: userInfo.username,
    name: userInfo.name,
    phone: userInfo.phone,
    email: userInfo.email,
    gender: '男',
    age: 25
  })
}

// 切换编辑模式
const toggleEditMode = () => {
  if (editMode.value) {
    // 取消编辑，恢复原始数据
    Object.assign(profileForm, {
      username: userInfo.username,
      name: userInfo.name,
      phone: userInfo.phone,
      email: userInfo.email
    })
  }
  editMode.value = !editMode.value
}

// 保存个人信息
const handleSaveProfile = async () => {
  try {
    await profileFormRef.value.validate()
    
    // 这里应该调用API更新用户信息
    Object.assign(userInfo, {
      name: profileForm.name,
      phone: profileForm.phone,
      email: profileForm.email
    })
    
    // 更新本地存储
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      const parsedUserInfo = JSON.parse(storedUserInfo)
      localStorage.setItem('userInfo', JSON.stringify({
        ...parsedUserInfo,
        ...userInfo
      }))
    }
    
    ElMessage.success('个人信息更新成功')
    editMode.value = false
  } catch (error) {
    console.error('个人信息验证失败:', error)
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    // 调用API修改密码
    const response = await axios.post('/api/user/change-password', {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    }, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.data.code === 200 || response.status === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      resetPasswordForm()
      
      // 密码修改成功后，清除登录状态并跳转到登录页面
      setTimeout(() => {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        router.push('/login')
      }, 2000)
    } else {
      ElMessage.error(response.data.message || '密码修改失败')
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error(error.response?.data?.message || '密码修改失败，请检查网络或稍后重试')
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  router.push(key)
}

// 页面加载时获取数据
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.user-profile-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 0;
  padding-bottom: 60px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 16px;
  opacity: 0.9;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.sidebar {
  width: 280px;
  flex-shrink: 0;
}

.user-info-card {
  background-color: white;
  border-radius: 8px;
  padding: 30px 20px;
  text-align: center;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.avatar-container {
  margin-bottom: 20px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info-card h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.user-email {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.profile-menu {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.main-content {
  flex: 1;
}

.profile-card,
.password-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header span {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

/* 表单样式优化 */
el-form {
  width: 100%;
}

el-form-item {
  margin-bottom: 20px;
}

el-input {
  width: 100%;
}

/* 按钮区域样式 */
el-form-item:last-child {
  text-align: center;
  padding-top: 10px;
}

el-button {
  margin: 0 10px;
  min-width: 80px;
}

@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
    padding: 0 10px;
  }
  
  .sidebar {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .profile-menu {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
  }
  
  .main-content {
    width: 100%;
    padding: 0;
  }
  
  .profile-card,
  .password-card {
    padding: 15px;
    margin-bottom: 15px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  el-form-item {
    margin-bottom: 15px;
  }
  
  el-button {
    margin: 5px;
    width: calc(50% - 10px);
    min-width: auto;
  }
}
</style>